package com.sis.edts.projectmanage.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.sis.edts.projectmanage.dto.TimeLine;
import com.sis.edts.projectmanage.entity.Project;
import com.sis.edts.projectmanage.service.IProjectService;
import com.sis.edts.projectmanage.service.IThingService;
import com.sis.base.dto.BaseResult;
import com.sis.base.util.RequestUtil;
import com.sis.edts.projectmanage.entity.Thing;
import com.xiaoleilu.hutool.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cutegl
 * @since 2017-08-07
 */
@Controller
@RequestMapping("/projectmanage/thing")
@Api(value = "事件接口", description = "事件接口")
public class ThingController {
    private final static Logger logger = LoggerFactory.getLogger(ThingController.class);
    @Autowired
    private IThingService thingService;
    @Autowired
    private IProjectService projectService;

    @ApiOperation(value = "新建事件", httpMethod = "POST")
    @RequestMapping(value = "/newThing", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult<Thing> newThing(@RequestBody Thing thing, HttpServletRequest request) {
        boolean isSuccess = true;
        try {
            thing.setThIP(RequestUtil.getIpAddr(request));
            thing.setThLastUpdateTime(DateUtil.date());
            isSuccess = thingService.insert(thing);
            Project project = projectService.selectById(thing.getProId());
            project.setWorkNum(project.getWorkNum() + thing.getThWorkNum());
            projectService.updateById(project);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new BaseResult<>(isSuccess, "新建事件失败");
        }
        return new BaseResult<>(isSuccess, "新建事件成功", thing);
    }

    @ApiOperation(value = "修改事件", httpMethod = "POST")
    @RequestMapping(value = "/updateThing", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult<Thing> updateThing(@RequestBody Thing thing, HttpServletRequest request) {
        boolean isSuccess = true;
        try {
            thing.setThLastUpdator(RequestUtil.getIpAddr(request));
            thing.setThLastUpdateTime(DateUtil.date());
            Thing oldThing = thingService.selectById(thing.getId());
            isSuccess = thingService.updateById(thing);
            Project project = projectService.selectById(thing.getProId());
            project.setWorkNum(project.getWorkNum() - oldThing.getThWorkNum() + thing.getThWorkNum());
            projectService.updateById(project);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new BaseResult<>(isSuccess, "修改事件失败");
        }
        return new BaseResult<>(isSuccess, "修改事件成功", thing);
    }

    @ApiOperation(value = "删除事件", httpMethod = "POST")
    @RequestMapping(value = "/deleteThing", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult<Thing> deleteThing(@RequestBody List<Integer> ids) {
        boolean isSuccess = true;
        try {
            for(int id:ids){
                Thing thing=thingService.selectById(id);
                Project project = projectService.selectById(thing.getProId());
                project.setWorkNum(project.getWorkNum()-thing.getThWorkNum());
                projectService.updateById(project);
            }
            isSuccess = thingService.deleteBatchIds(ids);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new BaseResult<>(isSuccess, "删除事件失败");
        }
        return new BaseResult<>(isSuccess, "删除事件成功");
    }

    @ApiOperation(value = "事件列表", httpMethod = "GET")
    @RequestMapping(value = "/thingList", method = RequestMethod.GET)
    @ResponseBody
    public BaseResult<List<Thing>> thingList(@RequestParam int proId) {
        List<Thing> list;
        try {
            EntityWrapper<Thing> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("pro_id", proId);
            entityWrapper.orderBy("th_last_update_time", false);
            list = thingService.selectList(entityWrapper);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new BaseResult<>(false, "获取事件列表失败");
        }
        return new BaseResult<>(true, list);
    }
    @ApiOperation(value = "查询事件", httpMethod = "GET")
    @RequestMapping(value = "/queryThing", method = RequestMethod.GET)
    @ResponseBody
    public BaseResult<List<Thing>> queryThing(@RequestParam String  thTitle,@RequestParam int  proId) {
        List<Thing> list;
        try {
            EntityWrapper<Thing> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("pro_id", proId);
            entityWrapper.like("th_title", thTitle);
            list = thingService.selectList(entityWrapper);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new BaseResult<>(false, "查询项目失败");
        }
        return new BaseResult<>(true, list);
    }

    @ApiOperation(value = "事件时间轴列表", httpMethod = "GET")
    @RequestMapping(value = "/timelineList", method = RequestMethod.GET)
    @ResponseBody
    public BaseResult<List<TimeLine>> timelineList(@RequestParam int proId) {
        List<Thing> list;
        List<TimeLine> timeLineList = new ArrayList<>();
        try {
            EntityWrapper<Thing> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("pro_id", proId);
            entityWrapper.orderBy("th_last_update_time", false);
            list = thingService.selectList(entityWrapper);
            for (Thing thing : list) {
                TimeLine timeLine = new TimeLine();
                Date thCreateDate = thing.getThCreateDate();
                if(thCreateDate==null) {
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(thCreateDate);
                    int year = cal.get(Calendar.YEAR);//获取年份
                    int month = cal.get(Calendar.MONTH) + 1;//获取月份
                    int date = cal.get(Calendar.DATE);//获取日
                    int day = cal.get(Calendar.DAY_OF_WEEK);//获取星期几
                    timeLine.setYear(year);
                    timeLine.setMonth(month);
                    timeLine.setDate(date);
                    timeLine.setDay(day);
                }
                timeLine.setThing(thing);
                timeLineList.add(timeLine);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new BaseResult<>(false, "获取事件列表失败");
        }
        return new BaseResult<>(true, timeLineList);
    }
}
